package com.guigu.dh.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * 这是通用的发送HttpClient请求的工具类
 *
 */




public class HttpClientRequestUtil {

    // post提交方法
    public static String doPost(String url,String jsonstr,String charset) {
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try{
            httpClient = new DefaultHttpClient();
            httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
            StringEntity se = new StringEntity(jsonstr, StandardCharsets.UTF_8);
            se.setContentType("text/json");
            se.setContentEncoding(new BasicHeader("Content-Type",
                    "application/json"));
            httpPost.setEntity(se);
            HttpResponse response = httpClient.execute(httpPost);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,charset);
                }
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return result;
    }

    // delete提交方法
    public static String doDelete(String url){
        HttpClient httpClient = null;
        HttpDelete httpDelete = null;
        String result = null;
        try{
            httpClient = new DefaultHttpClient();
            httpDelete = new HttpDelete(url);

            HttpResponse response = httpClient.execute(httpDelete);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,"UTF-8");
                }
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return result;
    }
}
